package com.example.tse.rbyair.widget.others;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.tse.rbyair.R;
import com.example.tse.rbyair.util.RbImageLoader;
import com.example.tse.rbyair.widget.imagecycleview.ADInfo;
import com.example.tse.rbyair.widget.imagecycleview.ImageCycleView;

import org.kymjs.kjframe.utils.DensityUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * @author KingKong
 * 视差滚动布局
 */
public class MyParallaxScrollView extends LinearLayout{
//	private GestureDetector gestureDetector;
//	private View.OnTouchListener onTouchListener;

    public MyParallaxScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
//        gestureDetector=new GestureDetector(new Yscroll() );
    }

    public MyParallaxScrollView(Context context) {
        super(context);
    }


    /**
     * background和foreground滚动的视差参数
     */
    private float mDiffFactor = 0;
    
    /**
     * child scrollview
     */
    private ParallaxInnerScrollView mForeground;
    
    /**
     * background
     */
    private View mBackgournd;
    
    /**
     * content
     */
    private LinearLayout mContent;
    
    /**
     * 视差滚动根布局
     */
    private View mParallaxScrollWidget;
    
    /**
     * 背景显示
     */
    private ImageCycleView mBackgroundContent;
    
    
    private View background_shade;
    
    /**
     * 国家 布局
     */
    private ImageView countryImg;
    private TextView countryName;
    private TextView discountTxt;
    private RelativeLayout country_rely;
    
    
    /**
     * 初始化
     */
    private void init() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        inflater.inflate(R.layout.my_parallax_scrollview, this);
        mParallaxScrollWidget = findViewById(R.id.parallax_scroll_widget);
        mBackgournd = findViewById(R.id.background);
//        background_shade = findViewById(R.id.background_shade);
        mBackgroundContent = (ImageCycleView)findViewById(R.id.background_content);
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mBackgroundContent.getLayoutParams();
        lp.height = DensityUtils.getScreenW(getContext());
        
        mForeground = (ParallaxInnerScrollView) findViewById(R.id.foreground);
        mForeground.setOnScrollListener(onScrollListener);
        
        countryImg = (ImageView)findViewById(R.id.countryImg);
        countryName = (TextView)findViewById(R.id.countryName);
        discountTxt = (TextView)findViewById(R.id.discountTxt);
        country_rely = (RelativeLayout)findViewById(R.id.country_rely);
        
//        mForeground.setOnTouchListener(new OnTouchListener() {
//
//			private float mLastY;
//
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				switch (event.getAction()) {
//				case MotionEvent.ACTION_DOWN:
//					mLastY = event.getY();
//					break;
//				case MotionEvent.ACTION_MOVE:
//					float y = event.getY();
//					RbLog.i("y - mLastY="+(y - mLastY));
//					
//					float alphaDelt = (y - mLastY) / 300;
//					float alpha = mBackgournd.getAlpha() + alphaDelt;
//					if (alpha > 1.0) {
//						alpha = 1.0f;
//					} else if (alpha < 0.0) {
//						alpha = 0.0f;
//					}
//					mBackgournd.setAlpha(alpha);
//					break;
//				case MotionEvent.ACTION_UP:
//					break;
//				}
//				return false;
//			}
//		});
        mContent = (LinearLayout) findViewById(R.id.content);
        transferChildren();
    }

    /**
     * 移动子view，将布局文件中设定的子view移动可滚动的view中
     */
    private void transferChildren() {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(0);
            if (child != mParallaxScrollWidget) {
                detachFromParent(child);
                mContent.addView(child);
            }
        }
    }
    
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (isInEditMode()) {
            return;
        }
        init();
    }
    
//    @Override
//	public boolean onInterceptTouchEvent(MotionEvent ev) {
//		return super.onInterceptTouchEvent(ev) && gestureDetector.onTouchEvent(ev);
//	}
//    
    class Yscroll extends SimpleOnGestureListener{

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
//			return super.onScroll(e1, e2, distanceX, distanceY);
			//控制手指滑动的距离
			if (Math.abs(distanceY)>=Math.abs(distanceX)) {
				return true;
			}
			return false;
		}

	}

    /**
     * 添加child到可滚动的视图当中
     * @param child child
     */
    public void addChildView(View child) {
        detachFromParent(child);
        mContent.addView(child);
    }

    /**
     * 添加child到可滚动的视图当中
     * @param child child
     * @param index index
     */
    public void addChildView(View child, int index) {
        detachFromParent(child);
        mContent.addView(child, index);
    }

    /**
     * 添加child到可滚动的视图当中
     * @param child child
     * @param width width
     * @param height height
     */
    public void addChildView(View child, int width, int height) {
        detachFromParent(child);
        mContent.addView(child, width, height);
    }
    
    
    /**
     * detach from parent
     * @param childView
     */
    private void detachFromParent(View childView) {
        if (null != childView) {
            ViewGroup parent = (ViewGroup) childView.getParent();
            if (null != parent) {
                parent.removeView(childView);
            }
        }
    }
    
    
//    /**
//     * 设置背景
//     * @param drawableId 
//     */
//    public void setBackgroundDrawableId(int drawableId) {
//        if (null != mBackgroundContent && drawableId >= 0) {
//            mBackgroundContent.setBackgroundResource(drawableId);
//        }
//    }
    
    /**
     * 设置背景
     */
    public void setBackgroundDrawableId(List<String> strs) {
        if (null != mBackgroundContent && strs.size() >= 0) {
        	ArrayList<ADInfo> infoList = new ArrayList<ADInfo>();
    		for(String s : strs){
    			ADInfo ad = new ADInfo();
    			ad.setUrl(s);
    			infoList.add(ad);
    		}
    		
            mBackgroundContent.setImageResources(infoList, new ImageCycleView.ImageCycleViewListener() {
    			
    			@Override
    			public void onImageClick(ADInfo info, int postion, View imageView) {
    				
    			}
    			
    			@Override
    			public void displayImage(String imageURL, ImageView imageView) {
    				RbImageLoader.displayImage(imageURL, imageView, RbImageLoader.getDetailSqureImageOptions());
    			}
    		});
        }
    }
    
    public void setCountryInfo(String img,String countryname,String discount){
    	if (countryImg!=null) {
    		RbImageLoader.displayImage(img, countryImg);
		}else {
			countryImg.setVisibility(View.INVISIBLE);
		}
		if(countryName!=null)
		countryName.setText(countryname);
		if(discount!=null)
		discountTxt.setText(discount + "折");
    }
    
    
    /* (non-Javadoc)
     * @see android.view.View#setBackgroundDrawable(android.graphics.drawable.Drawable)
     */
    public void setBackgroundDrawable(Drawable drawable) {
        if (null != drawable && null != mBackgroundContent) {
            mBackgroundContent.setBackgroundDrawable(drawable);
        }
    }
    
    /**
     * 设置前景
     * @param drawableId
     */
    public void setForegroundDrawableId(int drawableId) {
        if (null != mForeground && drawableId >= 0) {
            mForeground.setBackgroundResource(drawableId);
        }
    }
    
    /**
     * 设置前景
     * @param drawable
     */
    public void  setForegroundDrawable(Drawable drawable) {
        if (null != mForeground && null != drawable) {
            mForeground.setBackgroundDrawable(drawable);
        }
    }
    
    /**
     * 设置视差滚动参数
     * @param diffFactor
     */
    public void setDiffFactor(float diffFactor) {
        this.mDiffFactor = diffFactor;
        invalidate();
    }
    
    
    /**
     * background相对于屏幕可以滚动的距离
     */
    private int mBackgroundDiff;
    
    /**
     * foreground内容相对于屏幕可以滚动的距离
     */
    private int mForegroundDiff;

    
    /**
     * 视差因子，用于根据foreground滚动的距离来计算background的滚动
     */
    private float mParallaxFactor;
    
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (isInEditMode()) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        //先measure一次，以得到child的尺寸
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        
        int foregroundTotalHeight = getChildScrollViewTotalHeight();
        //计算需要额外布局的高度
        int scrollDiff = computeScrollDiffDistance(mBackgournd.getMeasuredHeight(), foregroundTotalHeight);
        int newBackgroundHeight = mBackgournd.getMeasuredHeight() + scrollDiff;
        //重新measure一下background
        measureChild(mBackgournd, widthMeasureSpec, MeasureSpec.makeMeasureSpec(newBackgroundHeight, MeasureSpec.EXACTLY));
        
        mBackgroundDiff = mBackgournd.getMeasuredHeight() - getMeasuredHeight();
        mForegroundDiff = foregroundTotalHeight - getMeasuredHeight();
        mParallaxFactor = ((float) mBackgroundDiff) / ((float) mForegroundDiff);
    }
    /**
     * 计算滚动差
     * @param backgroundHeight
     * @param forgroundHeight
     * @return 背景需要额外增加的高度
     */
    private int computeScrollDiffDistance(int backgroundHeight, int forgroundHeight) {
        if (forgroundHeight <= backgroundHeight) {
            return 0;
        }
        int heightDiff = forgroundHeight - backgroundHeight;
        int scrollDiff = (int) (heightDiff * mDiffFactor);
        return scrollDiff;
    }
    
    
    
    /**
     * 返回scrollview 内容高度（在onMeasure中或者结束后调用）
     * @return child scroll view的总高度
     */
    private int getChildScrollViewTotalHeight() {
        if (null == mContent) {
            return 0;
        }
        return mContent.getMeasuredHeight();
    }
    

    /**
     * forground滚动监听
     */
    private InnerScrollViewScrollListener onScrollListener = new InnerScrollViewScrollListener() {
        @Override
        public void onScroll() {
            int backgroundScrollY = (int) (mParallaxFactor * mForeground.getScrollY());
            
//          int i = mForeground.getScrollY();
            
//          RbLog.i("mForeground.getScrollY()="+mForeground.getScrollY() +"CommonUtils.dip2px(getContext(), 300)="+CommonUtils.dip2px(getContext(), 300));
            
            int nn = DensityUtils.getScreenW(getContext()) - mForeground.getScrollY();
//          RbLog.i("nn/CommonUtils.dip2px(getContext(), 300)="+(float)nn/CommonUtils.dip2px(getContext(), 300));
            
//			mBackgournd.setAlpha((float)nn/CommonUtils.dip2px(getContext(), 300));
			
            mBackgroundContent.setAlpha((float)nn/DensityUtils.getScreenW(getContext()));
            country_rely.setAlpha((float)nn/DensityUtils.getScreenW(getContext()));
            
            mBackgournd.scrollTo(0, backgroundScrollY);
        }
        
        
    };
    
    
    
    /**
     * @author yuanxingzhong
     * 监听forground 的滚动
     */
    public static interface InnerScrollViewScrollListener {
        public void onScroll();
    }
    
}
